﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace ShoeBoxScan {
  /// <summary>
  /// Interaction logic for UserImage.xaml
  /// </summary>
  public partial class UserImage : UserControl {


    public BitmapSource InputSource {
      get { return ( BitmapSource )GetValue( InputSourceProperty ); }
      set { SetValue( InputSourceProperty, value ); }
    }

    // Using a DependencyProperty as the backing store for InputSource.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty InputSourceProperty =
        DependencyProperty.Register( "InputSource", typeof( BitmapSource ), typeof( UserImage ), new UIPropertyMetadata( new PropertyChangedCallback((dp,dpe) => (dp as UserImage).Update())) );



    public CroppedBitmap OutputSource {
      get { return ( CroppedBitmap )GetValue( OutputSourceProperty ); }
      set { SetValue( OutputSourceProperty, value ); }
    }

    // Using a DependencyProperty as the backing store for OutputSource.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty OutputSourceProperty =
        DependencyProperty.Register( "OutputSource", typeof( CroppedBitmap ), typeof( UserImage ), new UIPropertyMetadata( null ) );



    public UserImage( ) {
      InitializeComponent( );
    }


    public bool Update( ) {

      
      var t = this.TransformToAncestor( this.Parent as Visual );

      var r = this.GetRotationTransform();

      var rune = r.TransformBounds( new Rect( this.GetCanvasLeft( ), this.GetCanvasTop( ), this.Width, this.Height ) );

      var p = t.TransformBounds( new Rect( this.GetCanvasLeft( ),this.GetCanvasTop(), this.Width, this.Height ) );

      var b = GetBounds(this,this.Parent as FrameworkElement );

      OutputSource = new CroppedBitmap( InputSource, new Int32Rect( ( int )rune.X, ( int )rune.Y, ( int )rune.Width, ( int )rune.Height ) );

      Output.Source = OutputSource;
      return true;
    }


    public Rect GetBounds( FrameworkElement of, FrameworkElement from ) {
      GeneralTransform transform = of.TransformToVisual( from );
      return transform.TransformBounds( new Rect( 0, 0, of.ActualWidth, of.ActualHeight ) );
    }


  }
}
